package com.yzx.yunyanzhengdemo.activity;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.btl.bean.Person;
import com.btl.cygf.MainActivity;
import com.btl.cygf.R;
import com.btl.cygf.TieZiActivity;
import com.btl.cygf.tool.AppConstant;
import com.btl.cygf.tool.Util;
import com.btl.http.HttpServies;
import com.btl.utils.MD5Encrypt;
import com.btl.utils.SavaPersonInfo;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.connect.auth.QQToken;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

public class LoginActivity extends Activity implements OnClickListener {

	private TextView mregisterText;
	private TextView Login_wangjimima;
	private ImageView login_backtofragment;
	private TextView login;
	private EditText login_user;
	private EditText login_password;
	private Person p;
	private String result;
	private LinearLayout qqlogin;
	private String openid;
	private String nickname;
	private String userlogo;
	private boolean value;

	private Tencent mTencent;
	public static QQAuth mQQAuth;
	public static String mAppid;
	private String vid;
	private Intent tit;
	private String type;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0x1123) {
				if (result.equals("账号或密码不正确")) {
					Toast.makeText(getApplicationContext(), result, 1).show();
					login_password.setText("");
				} else if (result.equals("封号状态")) {
					Toast.makeText(getApplicationContext(), result, 1).show();
					login_user.setText("");
					login_password.setText("");
				} else {
					getUserInfo();
				}

			}

			if (msg.what == 0x1124) {
				// 把回去的数据放到本地

				SavaPersonInfo.saveInfo(getApplicationContext(), p);

				// 跳转到我的页面

				if (!type.equals("1")) {
					Intent it = new Intent(LoginActivity.this,
							MainActivity.class);
					it.putExtra("type", 1);
					it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(it);

				} else {
					Intent it = new Intent(LoginActivity.this,
							TieZiActivity.class);
					it.putExtra("v_id", tit.getStringExtra("vid"));
					it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(it);

				}

			}

			if (msg.what == 0x1125) {
				Toast.makeText(getApplicationContext(), result, 0).show();
				// 把回去的数据放到本地
				if (result.equals("登录成功")) {
					updateLogo();
				}

			}

		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setNoTitle();
		setContentView(R.layout.login_activity);

		tit = getIntent();
		type = tit.getStringExtra("type");

		initView();
		setListener();
	}

	// 无标题
	public void setNoTitle() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	}

	private void initView() {
		// TODO Auto-generated method stub
		mregisterText = (TextView) findViewById(R.id.register);
		Login_wangjimima = (TextView) findViewById(R.id.Login_wangjimima);
		login_backtofragment = (ImageView) findViewById(R.id.login_backtofragment);
		login = (TextView) findViewById(R.id.login);
		login_user = (EditText) findViewById(R.id.Login_user);
		login_password = (EditText) findViewById(R.id.Login_password);
		qqlogin = (LinearLayout) findViewById(R.id.qqlogin);

	}

	private void setListener() {
		// TODO Auto-generated method stub
		mregisterText.setOnClickListener(this);
		login_backtofragment.setOnClickListener(this);
		login.setOnClickListener(this);
		qqlogin.setOnClickListener(this);
		Login_wangjimima.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.register:
			Intent it = new Intent(this, RegisterActivity.class);
			it.putExtra("type", "1");
			startActivity(it);
			break;
		case R.id.login_backtofragment:
			System.out.println();
			finish();
			break;
		case R.id.login:
			login();
			break;
		case R.id.qqlogin:
			qqlogin();
			break;
		case R.id.Login_wangjimima:
			Intent it1 = new Intent(this, RegisterActivity.class);
			it1.putExtra("type", "2");
			startActivity(it1);
			break;

		}

	}

	private void qqlogin() {
		// 这里的APP_ID请换成你应用申请的APP_ID，我这里使用的是DEMO中官方提供的测试APP_ID 222222
		mAppid = AppConstant.APP_ID;
		// 第一个参数就是上面所说的申请的APPID，第二个是全局的Context上下文，这句话实现了调用QQ登录
		mTencent = Tencent.createInstance(mAppid, getApplicationContext());
		System.out.println(mTencent);
		/**
		 * 通过这句代码，SDK实现了QQ的登录，这个方法有三个参数，第一个参数是context上下文，第二个参数SCOPO
		 * 是一个String类型的字符串，表示一些权限 官方文档中的说明：应用需要获得哪些API的权限，由“，”分隔。例如：SCOPE =
		 * “get_user_info,add_t”；所有权限用“all”
		 * 第三个参数，是一个事件监听器，IUiListener接口的实例，这里用的是该接口的实现类
		 */

		mTencent.login(LoginActivity.this, "all", new BaseUiListener());

	}

	private void updateLogo() {

		new Thread(new Runnable() {
			@Override
			public void run() {

				Map<String, String> params = new HashMap<>();
				params.put("id", openid);
				System.out.println("2" + openid);

				try {
					p = (Person) HttpServies.SendPostRequest(getResources()
							.getString(R.string.url) + "/CYGF/login.user",
							params, "utf-8", 3);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				handler.sendEmptyMessage(0x1124);
			}
		}).start();
	}

	private void login() {
		new Thread(new Runnable() {
			@Override
			public void run() {

				Map<String, String> params = new HashMap<>();
				params.put("id", login_user.getText().toString());
				params.put("pass", MD5Encrypt.getMD5Str(login_password
						.getText().toString()));

				try {
					result = (String) HttpServies.SendPostRequest(
							getResources().getString(R.string.url)
									+ "/CYGF/loginVerification.user", params,
							"utf-8", 2);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				handler.sendEmptyMessage(0x1123);
			}
		}).start();
	}

	private void getUserInfo() {
		new Thread(new Runnable() {
			@Override
			public void run() {

				Map<String, String> params = new HashMap<>();
				params.put("id", login_user.getText().toString());

				try {
					p = (Person) HttpServies.SendPostRequest(getResources()
							.getString(R.string.url) + "/CYGF/login.user",
							params, "utf-8", 3);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				handler.sendEmptyMessage(0x1124);
			}
		}).start();

	}

	/**
	 * 当自定义的监听器实现IUiListener接口后，必须要实现接口的三个方法， onComplete onCancel onError
	 * 分别表示第三方登录成功，取消 ，错误。
	 */
	private class BaseUiListener implements IUiListener {

		public void onCancel() {
			// TODO Auto-generated method stub

		}

		public void onComplete(Object response) {
			// TODO Auto-generated method stub

			try {
				// 获得的数据是JSON格式的，获得你想获得的内容
				// 如果你不知道你能获得什么，看一下下面的LOG

				openid = ((JSONObject) response).getString("openid");
				System.out.println(openid);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			/**
			 * 到此已经获得OpneID以及其他你想获得的内容了
			 * QQ登录成功了，我们还想获取一些QQ的基本信息，比如昵称，头像什么的，这个时候怎么办？
			 * sdk给我们提供了一个类UserInfo，这个类中封装了QQ用户的一些信息，我么可以通过这个类拿到这些信息
			 * 如何得到这个UserInfo类呢？
			 */
			QQToken qqToken = mTencent.getQQToken();
			UserInfo info = new UserInfo(getApplicationContext(), qqToken);
			// 这样我们就拿到这个类了，之后的操作就跟上面的一样了，同样是解析JSON
			info.getUserInfo(new IUiListener() {

				public void onComplete(final Object response) {

					JSONObject json = (JSONObject) response;

					try {
						userlogo = json.getString("figureurl_qq_2");
						nickname = json.getString("nickname");
						System.out.println(openid);

						new Thread(new Runnable() {

							@Override
							public void run() {
								Map<String, String> params = new HashMap<>();
								params.put("id", openid);
								params.put("nickname", nickname);
								params.put("avatar", userlogo);
								System.out.println("1" + openid);

								try {

									result = (String) HttpServies
											.SendPostRequest(getResources()
													.getString(R.string.url)
													+ "/CYGF/insertqq.user",
													params, "utf-8", 2);
									System.out.println(result);

								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								handler.sendEmptyMessage(0x1125);

							}
						}).start();

					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}

				public void onCancel() {

				}

				public void onError(UiError arg0) {

				}

			});

		}

		public void onError(UiError arg0) {
			// TODO Auto-generated method stub

		}

	}

}
